package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseRestartDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.EmployeeLoanContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * Created by lenovo on 2016/6/2.
 */
public class ManagelReimburseDetailFragment extends ManagelReimburseFragment {
  public static final String EXTRA_MANAGEREIMBURSE_CONTENT =
      "com.isunland.managesystem.ui.EXTRA_EXTRA_TRAVELREIMBURSE_CONTENT";
  private static final int REQUEST_DELETE = 0;
  private static final int REQUEST_ALTER = 1;
  private static final int REQUEST_RESATRT = 2;// 重新启动
  private static final int REQUEST_START = 3;// 启动
  private static final int REQUEST_STOP = 4;// 终止流程
  protected static final String EXTRA_CODE = "com.isunland.managesystem.ui.EXTRA_CODE";
  private EmployeeLoanContent mContent;

  @Override protected void setTitle() {
    // ( (BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.travelReimburse1);

  }

  @Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mContent = (EmployeeLoanContent) getArguments().getSerializable(EXTRA_MANAGEREIMBURSE_CONTENT);
    LogUtil.i("mrunId===" + mContent.getRunId());
  }

  // 创建菜单
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_employee_loan, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  // 菜单相应事件
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      // 修改,添加都是一个activity
      case R.id.menu_item_alter:
        if ("new".equals(mContent.getDataStatus()) || "abort".equals(mContent.getDataStatus())) {
          //                    Intent i = new Intent(getActivity(),TravelReimburseDetailActivity.class);
          //                    i.putExtra(EditeTravelReimburseFragment.EXTRA_TRAVELREIMBURSE_CONTENT,mContent);
          //                    i.putExtra(TravelReimburseDetailActivity.EXTRA_TYPE,TravelReimburseDetailActivity.EXTRA_EDITCONTENTTYPE);
          //
          //                    startActivityForResult(i, REQUEST_ALTER);
          Intent i = new Intent(getActivity(), ManageReimburseDetailActivity.class);
          i.putExtra(EditeManageReimburseFragment.EXTRA_TRAVELREIMBURSE_CONTENT, mContent);
          i.putExtra(ManageReimburseDetailActivity.EXTRA_TYPE,
              ManageReimburseDetailActivity.EXTRA_EDITCONTENTTYPE);

          startActivityForResult(i, REQUEST_ALTER);
        } else {
          Toast.makeText(getActivity(), R.string.draftOrAbort, Toast.LENGTH_SHORT).show();
        }
        break;

      // 删除
      case R.id.menu_item_delete:
        //			if (!mCurrentUser.getJobNumber().equalsIgnoreCase(
        //					mContent.getApplicantId())) {
        //				Toast.makeText(getActivity(), R.string.not_founder,
        //						Toast.LENGTH_SHORT).show();
        //				return true;
        //			}
        if ("new".equals(mContent.getDataStatus()) || "abort".equals(mContent.getDataStatus())) {

          showDialog(REQUEST_DELETE);
        } else {
          Toast.makeText(getActivity(), R.string.draftOrAbort, Toast.LENGTH_SHORT).show();
        }

        break;

      // 启动流程,草稿状态才可以启动
      case R.id.menu_item_startup:
        //判断当前登录人是否是登记人
        //			if (!mCurrentUser.getJobNumber().equalsIgnoreCase(
        //					mContent.getApplicantId())) {
        //				Toast.makeText(getActivity(), R.string.not_founder,
        //						Toast.LENGTH_SHORT).show();
        //				return true;
        //			}
        //			if ("new".equals(mContent.getDataStatus())) {
        //				showDialog(REQUEST_START);
        //			}
        if ("0".equals(mContent.getRunId())) {
          showDialog(REQUEST_START);
        } else if ("abort".equals(mContent.getDataStatus())) {

          showDialog(REQUEST_RESATRT);
        } else {
          Toast.makeText(getActivity(), R.string.ifstartup, Toast.LENGTH_SHORT).show();
        }
        break;
      //终止流程
      case R.id.menu_item_stop:
        //			Intent i=new Intent(getActivity(), StopTaskActivity.class);
        //			i.putExtra(StopTaskFragment.EXTRA_RUNID, mContent);
        //			startActivityForResult(i, REQUEST_STOP);
        if ("new".equals(mContent.getDataStatus())) {
          Toast.makeText(getActivity(), R.string.no_start, Toast.LENGTH_SHORT).show();
        } else if ("abort".equals(mContent.getDataStatus())
            || "checkPass".equals(mContent.getDataStatus())
            || DataStatus.PAID.equals(mContent.getDataStatus())
            || DataStatus.DOCUMENT.equals(mContent.getDataStatus())) {

          Toast.makeText(getActivity(), R.string.no_restart, Toast.LENGTH_SHORT).show();
        } else {
          showDialog(REQUEST_STOP);
        }
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyStop() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("runId", mContent.getRunId());
    LogUtil.i("终止流程params====" + params);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i("终止流程====" + arg0);
        try {
          MyUtils.dismissDialog();
          //解析
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          Toast.makeText(getActivity(), R.string.wrong_data, Toast.LENGTH_SHORT).show();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  /**
   * 显示时间对话框
   *
   * @param requestCode 请求码
   */
  public void showDialog(int requestCode) {
    DialogFragment dialog = null;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (requestCode) {
      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        break;

      case REQUEST_RESATRT:
        dialog =
            BaseRestartDialogFragment.newInstance(R.string.restart_message, R.string.restart_title);

        break;
      case REQUEST_START:
        dialog =
            BaseRestartDialogFragment.newInstance(R.string.start_up_hint, R.string.restart_title);

        break;
      case REQUEST_STOP:
        dialog = BaseRestartDialogFragment.newInstance(R.string.stop_hint, R.string.restart_title);

        break;
      default:
        break;
    }
    dialog.setTargetFragment(ManagelReimburseDetailFragment.this, requestCode);
    dialog.show(fm, "");
  }

  // 终止流程重新启动
  private void volleyReStart() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RESTART_UP);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("runId", mContent.getRunId());
    LogUtil.i(mContent.getRunId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          //重新启动时的错误log日志
          LogUtil.i(workProcess.getMessage());

          ToastUtil.show(R.string.failstartup);
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.failstartup, Toast.LENGTH_SHORT).show();

          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          vollyStart();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DELETE) {
      vollyDelete();// 删除
      return;
    }
    if (requestCode == REQUEST_START) {
      vollyStart();
      return;
    }
    if (requestCode == REQUEST_RESATRT) {
      volleyReStart();
      return;
    }
    if (requestCode == REQUEST_ALTER) {

      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
      return;
    }
    if (requestCode == REQUEST_STOP) {

      //			getActivity().setResult(Activity.RESULT_OK);
      //			getActivity().finish();
      volleyStop();
      return;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  // 删除
  private void vollyDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("id", mContent.getId());
    if (!(mContent.getRunId()).equals("0")) {
      params.put("runId", mContent.getRunId());
    }
    params.put("type", "mobile");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage[] result = new Gson().fromJson(arg0, SuccessMessage[].class);
        SuccessMessage workProcess = result[0];
        if (null == workProcess || null == workProcess.getResult()) {
          ToastUtil.show(R.string.failure_operation);
          //					LogUtil.isSaveLog=true;
          //重新启动时的错误log日志
          LogUtil.e(workProcess.getMessage());
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          ToastUtil.show(R.string.failure_operation);
          LogUtil.i(workProcess.getMessage());
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  // 启动流程
  private void vollyStart() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_START_UP);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("isList", "1");
    params.put("id", mContent.getId());
    params.put("recFlowKey", mContent.getFlowFlag());
    params.put("certificateCode", mContent.getCertificateCode());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          ToastUtil.show(R.string.failure_operation);
          //					LogUtil.isSaveLog=true;
          //重新启动时的错误log日志
          LogUtil.e(workProcess.getMessage());
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          ToastUtil.show(R.string.failure_operation);
          LogUtil.i(workProcess.getMessage());
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

	/*
   * 初始化控件
	 */

  @Override protected void initData() {
    tvcertificateNo.setText(mContent.getCertificateNo());
    tvsumBorrow.setText(mContent.getSumBorrow());
    tvregStaffName.setText(mCurrentUser.getRealName());
    tvapplicantName.setText(mCurrentUser.getRealName());
    tvapplyTime.setText(mContent.getApplyTime());
    //合同    顺序：项目  订单  合同
    //		tvcontractId.setText(mContent.getContractName());
    if (!TextUtils.isEmpty(mContent.getContractProjectName())) {
      tvcontractId.setText(mContent.getContractProjectName());
    }
    if (!TextUtils.isEmpty(mContent.getOrderName())) {
      tvcontractId.setText(mContent.getOrderName());
    }
    if (!TextUtils.isEmpty(mContent.getContractName())) {
      tvcontractId.setText(mContent.getContractName());
    }

    ibcontract.setVisibility(View.GONE);
    etexpenseDesc.setText(mContent.getExpenseDesc());
    etpoutAmount.setText(mContent.getToutAmount());
    etoffBorrow.setText(mContent.getOffBorrow());// 冲抵金额
    ettoutAmount.setText(mContent.getPoutAmount());
    etexpenseDesc.setEnabled(false);
    etpoutAmount.setEnabled(false);
    ettoutAmount.setEnabled(false);

    // RadioButton点击事件，是否冲抵借款
    tag = mContent.getIfOffBorrow();
    if (("T").equals(tag)) {

      rbtrueOffset.setChecked(true);
      rbfalseOffset.setChecked(false);
      rbfalseOffset.setEnabled(false);
    } else {
      rbtrueOffset.setChecked(false);
      rbfalseOffset.setChecked(true);
      rbtrueOffset.setEnabled(false);
    }
    etoffBorrow.setEnabled(false);

    //票据

    //		tvsumPrebill.setText(mContent.getSumPrebill());//合计预存票据
    //		if (mContent.getBillNo()==null) {
    //			mContent.setBillNo("");
    //		}
    ////		etbillNo.setText(mContent.getBillNo());
    //		etnobillAmount.setText(mContent.getNobillAmount());
    //		tvreplenishAmount.setText(mContent.getReplenishAmount());//本次预存票据

    //        etbillAmount.setText(mContent.getBillAmount());
    //        etdeductionAmount.setText(mContent.getDeductionAmount());

    etpayeeBank.setText(mContent.getPayeeBank());
    etpayeeAccname.setText(mContent.getPayeeAccname());
    etpayeeAccount.setText(mContent.getPayeeAccount());

    tvfownerkindName.setText(mContent.getFownerkindName());//归属分类
    tvappobjectName.setText(mContent.getAppobjectName());//归属对象
    ibfownerkindName.setVisibility(View.GONE);
    ibappobjectName.setVisibility(View.GONE);

    //		etbillNo.setEnabled(false);
    //		etbillAmount.setEnabled(false);
    //		etnobillAmount.setEnabled(false);
    etpayeeBank.setEnabled(false);
    etpayeeAccname.setEnabled(false);
    etpayeeAccount.setEnabled(false);

    //附件
    if (mContent.getFileOriginalName() == null || TextUtils.isEmpty(
        mContent.getFileOriginalName())) {
      //			mContent.setFileOriginalName("");
      mTvExtra.setVisibility(View.GONE);
      mIvExtra.setVisibility(View.GONE);
    } else {
      mTvExtra.setText(mContent.getFileOriginalName());
      mIvExtra.setVisibility(View.GONE);
      //点击附件名，下载附件
      mTvExtra.setOnClickListener(new View.OnClickListener() {

        @Override public void onClick(View v) {
          ExtraDownLoadDialogFragment dialog =
              ExtraDownLoadDialogFragment.newInstance("", mContent.getFilePath());
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.show(fm, "");
        }
      });
    }
  }

  // fragment之间传值
  public static ManagelReimburseDetailFragment newInstance(EmployeeLoanContent item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_MANAGEREIMBURSE_CONTENT, item);
    ManagelReimburseDetailFragment fragment = new ManagelReimburseDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}

